<?php
session_start();

//连接数据库
try {
    function success(){
        $result=[
            'error' => 0,
            'message' => '成功'
        ];
        return json_encode($result);
    }
    function error($mag){
        $data = [
            'error' => 1,
            'message' => $mag
        ];
        return json_encode($data);
    }
    //文件上传
    if(!isset($_FILES['userImg'])){
        die('无文件上传');
    };
    if($_FILES['userImg']['error'] != 0){
        die('无文件上传');
    };
    $allow=[
        'image/.jpeg',
        'image/.png',
        'image/.gif'
    ];
    if(in_array($_FILES['userImg']['type'],$allow)){
        die('禁止上传该类型！');
    };
    $file_name=$_FILES['userImg']['name'];
    $file_name=explode('.',$file_name)[1];
    $file_name=$_POST['username'].'.'.$file_name;
    $file_name='../upload/'.$file_name;
    move_uploaded_file($_FILES['userImg']['tmp_name'],$file_name);
    //连接数据库
    $db = new PDO('mysql:dbname=liaotian;host=106.14.7.147','root','123456');

    $add= $db->prepare('UPDATE user SET password=:password,repassword=:repassword,nicheng=:nicheng,sex=:sex,userImg=:userImg WHERE username=:username');
    $data[':username']= $_POST['username'];
    $data[':password']=$_POST['password'];
    $data[':repassword']=$_POST['repassword'];
    $data[':nicheng']=$_POST['nicheng'];
    $data[':sex']=$_POST['sex'];
    $data[':userImg']=$file_name;

    if($add->execute($data) === false){
        print_r($add->errorInfo());
    }
    $re=$add->fetch();
    if(empty($_POST['password'])){
        die(error('密码不能为空'));
    }
    if(empty($_POST['repassword'])){
        die(error('重复密码不能为空'));
    }
    if(empty($_POST['nicheng'])){
        die(error('昵称不能为空'));
    }
    if(empty($_FILES['userImg'])){
        die(error('头像不能为空'));
    }
    if($_POST['repassword'] != $_POST['password']){
        die(error('密码不一致'));
    }
    echo success();
} catch (PDOException $e) {
    echo 'Connection failed';
}
